import React from 'react';

type ErrorBoundaryProps = {
  errorContent?: React.ReactNode;
};

export class ErrorBoundary extends React.PureComponent<ErrorBoundaryProps, { hasError: boolean }> {
  constructor(props: ErrorBoundaryProps) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError(error: Error) {
    if (error.message.includes('Failed to fetch dynamically imported module')) {
      // 文件加载失败， 自动刷新页面
      window.location.reload();
    }

    return { hasError: true };
  }

  componentDidCatch(error: Error, errorInfo: any) {
    if (error.message.includes('Failed to fetch dynamically imported module')) {
      // 文件加载失败， 自动刷新页面
      window.location.reload();
    }
  }

  render() {
    if (this.state.hasError) {
      // You can render any custom fallback UI
      return this.props.errorContent;
    }

    return this.props.children;
  }
}

window.addEventListener(
  'error',
  error => {
    if (error?.message?.includes('Failed to fetch dynamically imported module')) {
      // 文件加载失败， 自动刷新页面
      window.location.reload();
    }
  },
  true
);
